<?php

/**
 * user actions.
 *
 * @package    Bookstore
 * @subpackage user
 * @author     Enkuso
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{
    public function preExecute()
    {
        parent::preExecute();

        $this->forward404Unless($this->getRequest()->hasParameter('token'));
    }

    /**
     * Хэрэглэгчийн дэлгэрэнгүй мэдээлэл авах
     */
    public function executeInfo(sfWebRequest $request)
    {
        $user = $this->getUser()->getGuardUser();

        if($user){
            $this->user = array(
                'username'  => $user->getUsername(),
                'firstname' => $user->getFirstName(),
                'lastname'  => $user->getLastName(),
                'email'     => $user->getEmailAddress(),
                'is_active' => $user->getIsActive(),
                'last_login' => $user->getLastLogin(),
                'registered_date' => $user->getCreatedAt(),
                'is_admin' => $user->getIsSuperAdmin(),
            );
            $this->stat = 'ok';
        } else {
            $this->stat = 'fail';
        }
    }

    /**
     * Хэрэглэгчийн ном үзсэн түүх
     */
    public function executeHistory(sfWebRequest $request)
    {
        $this->history = array();

        $page = $request->getParameter('page', 1);
        $limit = $request->getParameter('limit', sfConfig::get('app_max_per_page'));

        $from = $request->getParameter('from_date', null);
        $to = $request->getParameter('to_date', null);

        $user = $this->getUser()->getGuardUser();

        $history = ViewHistoryTable::getInstance()->getViewHistory($user->getId(), $page, $limit, $from, $to);

        if($history && count($history)){
            foreach ($history as $h)
            {
                $this->history[$h->getBook()->getId()] = $h->getBook()->shortInfoAsArray();
                $this->history[$h->getBook()->getId()]['viewed_date'] = $h->getViewedAt();
            }
            $this->page = $page;
            $this->perpage = $limit;
            $this->total = ViewHistoryTable::getInstance()->getViewHistoryCount($user->getId());
            $this->pages = ceil($this->total / $this->perpage);
            $this->stat = 'ok';
        } else {
            $this->stat = 'fail';
            $this->error_code = 404;
            $this->error_msg = apiErrors::getErrorMessage($this->error_code);
        }

    }
}
